package section4_10;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * Created by Hyman on 2017/6/8.
 *
 * 在执行器中控制任务的完成
 */
public class Main {

    public static void main(String[] args) {

        // 创建一个执行器对象
        ExecutorService executor = (ExecutorService) Executors.newCachedThreadPool();

        ResultTask[] tasks = new ResultTask[5];
        for(int i=0; i<5; i++) {
            ExecutableTask executableTask = new ExecutableTask("Task " + i);
            tasks[i] = new ResultTask(executableTask);
            executor.submit(tasks[i]);
        }

        // 休眠5秒钟
        try {
            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException e1) {
            e1.printStackTrace();
        }

        // 取消所有的任务，如果任务在取消之前已经完成，取消操作对任务没有任何影响
        for (ResultTask resultTask : tasks) {
            resultTask.cancel(true);
        }

        // 输出未被取消的任务的结果
        for (ResultTask resultTask : tasks) {
            try {
                if (!resultTask.isCancelled()) {
                    System.out.printf("%s\n", resultTask.get());
                }
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }
        }

        // 关闭执行器
        executor.shutdown();

    }

}
